import {
 getRepaymentTaskId, createWorkTask, getTaskUser, actionTaskUser
} from '@/api/flow/work';
import { START_ACTION } from '@/utils/actions';

export default {
  data() {
    return {
      workDetails: {},
      repayment_task_id: ''
    };
  },

  methods: {
    // action data
    actionData() {
      const { task_node } = this.workDetails;
      return {
        task_node: task_node.id,
        choice_child: [],
        // 表单名称
        work_name: '还款',
        // 表单数据
        fields_data: [],
        order_id: this.settlement.orders
      };
    },

    // Action 提交
    submitAction(action = START_ACTION) {
      return new Promise((resolve, reject) => {
        actionTaskUser(this.repayment_task_id, action, this.actionData())
          .then(async ({ status, message }) => {
            resolve({ status, message });
          })
          .catch((err) => {
            reject(err);
          })
          .finally(() => {});
      });
    },

    // 获取工单信息
    getWorkTask(tid) {
      return new Promise((resolve, reject) => {
        getTaskUser(this.repayment_task_id)
          .then((response) => {
            this.workDetails = response;
            resolve(response);
          })
          .catch((err) => reject(err));
      });
    },

    async submitRepayment() {
      const { amount, stage } = this.settlement;

      this.formLoading = true;

      try {
        // 重新计算
        // await this.getRepayments();
        // this.$refs.repaymentsRef.rangeSelect(0, (stage - 1), true);

        // 创建工单
        await this.createProccess();
        await this.getWorkTask();

        // 发起工单
        await this.submitAction(START_ACTION);

        const { tid, repayment_task_id: tr_id } = this;

        this.$router.push({
          name: 'RepaymentResult',
          params: { tid, tr_id }
        });

        this.formLoading = false;
      } catch (error) {
        console.log(error);
        this.formLoading = false;
      } finally {
      }
    },

    // 创建借款流程
    async createProccess() {
      try {
        const data = await this.getTaskId();

        const res = await createWorkTask(data.alias_id);
        this.repayment_task_id = res.task_id;

        return res;
      } catch (error) {
        throw new Error(error);
      }
   },

    // 获取id
    async getTaskId() {
      try {
       const res = await getRepaymentTaskId(this.tid);

       return res;
     } catch (error) {
       throw new Error(error);
     }
   }
  }
};
